<script setup>
import { User, Lock } from "@element-plus/icons-vue";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// 本地缓存
import { useUserInfoStore } from "@/stores/userInfo";
// 接口服务
import {
  userRegisterService,
  userLoginService,
  getUserInfoService,
} from "@/api/user";
import { getAddressListService } from "@/api/address";
const router = useRouter();

//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false);

// 表单数据模型
const formData = ref({
  userAccount: "",
  userPassWord: "",
  rePassWord: "",
});

// 校验密码函数
const checkRePassWord = (rule, value, callback) => {
  if (value == "") {
    callback(new Error("请再次输入密码"));
  } else if (value != formData.value.userPassWord) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const isValidUsername = (value) => /^[A-Za-z0-9]+$/.test(value);
const isValidPassword = (value) => /^[A-Za-z0-9]+$/.test(value);

const rules = {
  userAccount: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!isValidUsername(value)) {
          callback(new Error("用户名只能包含字母和数字"));
        } else if (value.length < 5 || value.length > 16) {
          callback(new Error("用户名长度在5到16个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  userPassWord: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!isValidPassword(value)) {
          callback(new Error("密码只能包含字母和数字"));
        } else if (value.length < 5 || value.length > 16) {
          callback(new Error("密码长度在5到16个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  rePassWord: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: checkRePassWord, trigger: "blur" },
  ],
};

// 提交表单数据校验函数
const submitFormCheck = (str) => {
  if (str == "register") {
    form.value.validate((valid) => {
      if (!valid) return;
      register();
    });
  } else if (str == "login") {
    form.value.validate((valid) => {
      if (!valid) return;
      login();
    });
  }
};

// 登录函数
const userInfoStore = useUserInfoStore();
const form = ref(null);

const login = async () => {
  let result = await userLoginService(formData.value);
  if (result.code !== 0) {
    ElMessage.error("账号或密码错误！");
    return;
  }
  ElMessage.success("登录成功！");
  // token存入本地缓存
  userInfoStore.setToken(result.data);
  // 用户数据存入本地缓存
  result = await getUserInfoService();
  console.log(result);
  userInfoStore.setInfo(result.data);
  // 用户地址存入本地缓存
  result = await getAddressListService();
  userInfoStore.setAddress(result.data);
  // 跳转到首页
  router.push("/");
};

// 注册函数
const register = async () => {
  let result = await userRegisterService(formData.value);
  if (result.code != 0) {
    return;
  }
  ElMessage.success("注册成功，请返回登录页面进行登录！");
  // 跳转到登录页面

  router.push("/login");
}; // 定义函数，用于清空formData数据模型

const clearFormData = () => {
  formData.value = {
    username: "",
    repassword: "",
    password: "",
  };
};
</script>
<template>
  <div class="common-layout">
    <el-container>
      <el-header></el-header>
      <el-main class="main-content">
        <!-- logo图标 -->
        <router-link to="/">
          <img
            src="@/assets/images/logo/轩宝阁.png"
            style="width: 200px; margin: 0 auto; display: block"
          />
        </router-link>
        <el-row :gutter="1">
          <el-col :span="12" :offset="1" class="form">
            <!-- 注册表单 -->
            <el-form
              ref="form"
              size="large"
              autocomplete="off"
              v-if="isRegister"
              :model="formData"
              :rules="rules"
            >
              <el-form-item>
                <h1>注册</h1>
              </el-form-item>
              <el-form-item prop="userAccount">
                <el-input
                  :prefix-icon="User"
                  placeholder="请输入用户名"
                  v-model="formData.userAccount"
                ></el-input>
              </el-form-item>
              <el-form-item prop="userPassWord">
                <el-input
                  :prefix-icon="Lock"
                  type="password"
                  placeholder="请输入密码"
                  v-model="formData.userPassWord"
                ></el-input>
              </el-form-item>
              <el-form-item prop="rePassWord">
                <el-input
                  :prefix-icon="Lock"
                  type="password"
                  placeholder="请输入再次密码"
                  v-model="formData.rePassWord"
                ></el-input>
              </el-form-item>
              <!-- 注册按钮 -->
              <el-form-item>
                <el-button
                  class="button"
                  type="primary"
                  auto-insert-space
                  @click="submitFormCheck('register')"
                >
                  注册
                </el-button>
              </el-form-item>
              <el-form-item class="flex">
                <el-link
                  type="info"
                  :underline="false"
                  @click="
                    isRegister = false;
                    clearFormData();
                  "
                >
                  ← 返回
                </el-link>
              </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form
              ref="form"
              size="large"
              autocomplete="off"
              v-else
              :model="formData"
              :rules="rules"
            >
              <el-form-item>
                <h1>登录</h1>
              </el-form-item>
              <el-form-item prop="userAccount">
                <el-input
                  :prefix-icon="User"
                  placeholder="请输入用户名"
                  v-model="formData.userAccount"
                ></el-input>
              </el-form-item>
              <el-form-item prop="userPassWord">
                <el-input
                  name="userPassWord"
                  :prefix-icon="Lock"
                  type="password"
                  placeholder="请输入密码"
                  v-model="formData.userPassWord"
                ></el-input>
              </el-form-item>
              <el-form-item class="flex">
                <div class="flex">
                  <el-checkbox v-model="userInfoStore.remember"
                    >记住我</el-checkbox
                  >
                  <el-link type="primary" :underline="false"
                    >忘记密码？</el-link
                  >
                </div>
              </el-form-item>
              <!-- 登录按钮 -->
              <el-form-item
                @keydown="
                  (event) => event.key === 'Enter' && submitFormCheck('login')
                "
              >
                <el-button
                  class="button"
                  type="primary"
                  auto-insert-space
                  @click="submitFormCheck('login')"
                  >登录</el-button
                >
              </el-form-item>
              <el-form-item class="flex">
                <el-link
                  type="info"
                  :underline="false"
                  @click="
                    isRegister = true;
                    clearFormData();
                  "
                >
                  注册 →
                </el-link>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="1">
            <!-- 栅栏隔板 -->
            <div
              style="
                background-color: #909399;
                width: 2px;
                height: 300px;
                margin: 50px 50px;
                border-radius: 15px;
              "
            >
              <img style="height: 300px;width: 300px; margin-left: 50px;" src="@/assets/images/生成二维码图片.png"/>
            </div>
          </el-col>
          <el-col :span="7" :offset="2">二维码登录区</el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped lang = "scss">
@import "@/assets/style/config.scss";
.main-content {
  background-color: #fff;
  width: 60%;
  margin: 0 auto;
  margin-top: 100px;
  border-radius: 10px;
}
.common-layout {
  background-image: linear-gradient(to right, #2a4c65, #a6c1ee);
  height: 97.5vh;
}

.form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  user-select: none;

  .title {
    margin: 0 auto;
  }

  .button {
    width: 100%;
  }

  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>